package com.cardbaobao.cardbabyclient.buried;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cardbaobao.cardbabyclient.model.BuriedData;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.LogUtils;
import com.cardbaobao.cardbabyclient.utils.NetUtil;
import com.cardbaobao.cardbabyclient.utils.SharedPreferencesUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by Jiangzx on 2017/11/13 10:24.
 * 公司数据埋点工具类
 */

public class SelfUtils {
    private static final String TAG="Buried";
    private static final int READ_TIME_OUT=10000;//10秒
    private static final int WRITE_TIME_OUT=15000;//15秒
    private static final int CONNECTION_TIME_OUT=20000;//20秒


    private static OkHttpClient okHttpClient;
    private static synchronized void initOkHttpClient(){
        if(okHttpClient==null){
            okHttpClient=new OkHttpClient.
                    Builder().
                    readTimeout(READ_TIME_OUT,TimeUnit.MILLISECONDS).
                    writeTimeout(WRITE_TIME_OUT,TimeUnit.MILLISECONDS).
                    connectTimeout(CONNECTION_TIME_OUT, TimeUnit.MILLISECONDS).
                    build();
        }
    }


    /**
     * 埋点点击行为
     * @param actionId 点击事件编号
     * @param actionName 点击事件名称
     * @param enterPageTime 进入页面时间毫秒数
     * @param currentPageId 当前页面id
     * @param prePageId 进入此页面的页面id
     */
    public static void buriedClickData(String actionId,
                                       String actionName,
                                       long enterPageTime,
                                       String currentPageId,
                                       String prePageId){
        BuriedData.PostData postData=new BuriedData.PostData();
        BuriedData.ClickData clickData=
                new BuriedData.ClickData(actionId,actionName);
        BuriedData.BrowseData browseData=
                new BuriedData.BrowseData(enterPageTime,
                        currentPageId,
                        prePageId);
        postData.setClick_data(clickData);
        postData.setBrowse_data(browseData);
        postBuriedData(postData);
    }


    /**
     * 埋点浏览行为
     * @param enterPageTime 进入当前页面的时间
     * @param currentPageId 当前页面id
     * @param prePageId 进入此页面的页面id
     */
    public static void buriedBrowseData(long enterPageTime,
                                        String currentPageId,
                                        String prePageId){
        BuriedData.PostData postData=new BuriedData.PostData();
        BuriedData.BrowseData browseData=
                new BuriedData.BrowseData(enterPageTime,
                        currentPageId,
                        prePageId);
        postData.setBrowse_data(browseData);
        postBuriedData(postData);
    }

    private static void postBuriedData(BuriedData.PostData postData){
        BuriedData.BaseData baseData=postData.getBase_data();
        //设置经纬度
        baseData.setLocation(SharedPreferencesUtil.LocationInfo.getCityLongitude()+
                ","+SharedPreferencesUtil.LocationInfo.getCityLatitude());
        //设置网络访问途径
        baseData.setSignal_mode(NetUtil.getAccessChannel(ApplicationHelper.getApplicationContext()));
        post(URLUtil.DATA_BURIED_URL,
                "logInfo",
                JSONObject.toJSONString(postData, SerializerFeature.WriteMapNullValue)).
                subscribeOn(Schedulers.newThread()).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {

                    }
                });
    }

    /**
     * post请求
     * @param url 请求url
     * @param paramsKey 请求参数key
     * @param params 请求参数值
     * @return rx observable
     */
    public static Observable<String> post(final String url,
                                          final String paramsKey,
                                          final String params){
        if(okHttpClient==null){
            initOkHttpClient();
        }
        final Observable.OnSubscribe<String> onSubscribe=
                new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        Request.Builder requestBuilder=new Request.Builder().url(url);
                        FormBody.Builder bodyBuilder=new FormBody.Builder();
                        if(!TextUtils.isEmpty(paramsKey)&&!TextUtils.isEmpty(params)){
                            bodyBuilder.add(paramsKey,params);
                            requestBuilder.post(bodyBuilder.build());
                        }
                        Request request=requestBuilder.build();
                        try{
                            Response response=okHttpClient.newCall(request).execute();
                            if(response.isSuccessful()){
                                //请求成功
                                String result=response.body().string();
                                LogUtils.d(TAG,"success\nurl:"+url+
                                        "\nparamsKey:"+paramsKey+
                                        "\nparams:"+params+
                                        "\nresult:"+result);
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            }else{
                                //请求失败
                                int code=response.code();
                                LogUtils.w(TAG,"success\nurl:"+url+
                                        "\nparamsKey:"+paramsKey+
                                        "\nparams:"+params+
                                        "\nresponseCode:"+code);
                                Exception e=new RuntimeException("请求异常,code:"+code);
                                subscriber.onError(e);
                            }
                        }catch (Exception e){
                            LogUtils.e(TAG,"error\nurl:"+url+
                                    "\nparamsKey:"+paramsKey+
                                    "\nparams:"+params+
                                    "\n"+e.getMessage());
                            subscriber.onError(e);
                        }
                    }
                };
        return Observable.unsafeCreate(onSubscribe);
    }
}
